/**
 * Copyright 2009 University of  Washington
 * This code is released under the GPL version 3 - with a copy of the license included
 * @author Maya Hao Li
 *
 */
package seedpod.webapp.service;

/**
 * SHA encripton of password, one way hash
 * code copyright http://www.devbistro.com/articles/Java/Password-Encryption
 */
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;

public final class PasswordService
{
  private static PasswordService _instance;

  private PasswordService()
  {
  }

  public synchronized String encrypt(String plaintext) throws SystemUnavailableException
  {
    MessageDigest md = null;
    try
    {
      md = MessageDigest.getInstance("SHA"); //step 2
    }
    catch(NoSuchAlgorithmException e)
    {
      throw new SystemUnavailableException(e.getMessage());
    }
    try
    {
      md.update(plaintext.getBytes("UTF-8")); //step 3
    }
    catch(UnsupportedEncodingException e)
    {
      throw new SystemUnavailableException(e.getMessage());
    }

    byte raw[] = md.digest(); //step 4
    String hash = (new BASE64Encoder()).encode(raw); //step 5
    return hash; //step 6
  }
  
  public static synchronized PasswordService getInstance() //step 1
  {
    if(_instance == null)
    {
       _instance = new PasswordService(); 
    } 
    return _instance;
  }
  
  
  public static void main(String[] args) {
	String password1 = "seedpod";
	String password2 = "seedpod";
	try {
		String enc1 = PasswordService.getInstance().encrypt( password1 );
		String enc2 = PasswordService.getInstance().encrypt( password2 );
		System.out.println( enc1 );
		System.out.println( "test enc1 = enc2:  " + enc1.equals( enc2 ));
	}
	catch (SystemUnavailableException e) {
		System.err.println(e.getMessage());
	}
  }
}